const tbodyBox = document.querySelector('.list')
const bsModal = new bootstrap.Modal(document.querySelector('#modal'))
let studentId = 0

//===获取数据===
//1.获取学生列表数据
async function getStudentList(){
    try {
        let res = await axios({url:'/students'})
        return res  // {message:'',data:[{}]}
    } catch (error) {
        pxmu.fail(error.response && error.response.data.message || '获取学生数据异常，检查网络')
    }
}
//2.省市区数据获取

//2.1获取省份数据
async function getProvinceList(){
    try {
        return await axios.get('/api/province')
    } catch (error) {
        pxmu.fail(error.response&&error.response.data.message || '获取省份数据异常，检查网络')
    }
}

//2.2获取省份数据
async function getCityList(pname){
    try {
        return await axios.get('/api/city?pname='+pname)
    } catch (error) {
        pxmu.fail(error.response&&error.response.data.message || '获取城市数据异常，检查网络')
    }
}

//2.3获取省份数据
async function getAreaList(pname,cname){
    try {
        return await axios.get(`/api/area?pname=${pname}&cname=${cname}`)
    } catch (error) {
        pxmu.fail(error.response&&error.response.data.message || '获取区数据异常，检查网络')
    }
}

//3.获取学生数据
async function getStudentInfoData(id){
    try {
        return await axios({url:`/students/${id}`})
    } catch (error) {
        pxmu.fail(error.response&&error.response.data.message||'获取学生详情失败')
    }
}

//4.修改学生详情
async function putStudentInfoData(id,body){
    try {
        return await axios({url:`/students/${id}`,method:'PUT',data:body})
    } catch (error) {
        pxmu.fail(error.response&&error.response.data.message||'修改学生详情失败')
    }
}

//5.新增学生数据
async function postNewStudent(body){
    try {
         await axios({url:`/students`,method:'POST',data:body})
    } catch (error) {
        pxmu.fail(error.response&&error.response.data.message || '新增学生失败')
    }
}

//6.删除学生功能
async function delStudent(id){
    try {
        await axios({url:`/students/${id}`,method:'delete'})
    } catch (error) {
        pxmu.fail(error.response&&error.response.data.message || '删除学生失败')
    }
}

//===渲染数据===

// 1.渲染学生列表
async function renderStudentList(){
    let {data} = await getStudentList()
    let str = ''
    data.forEach(item=>{
        str+=`
        <tr>
        <td>${item.name}</td>
        <td>${item.age}</td>
        <td>${item.gender == 0?'男':'女'}</td>
        <td>第${item.group}组</td>
        <td>${item.hope_salary}</td>
        <td>${item.salary}</td>
        <td>${item.province}${item.city}${item.area}</td>
        <td>
        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen" data-id="${item.id}"></i></a>
        <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id="${item.id}"></i></a>
        </td>
    </tr>
        `
    })
    document.querySelector('.total').innerText=data.length
    tbodyBox.innerHTML = str
}
// 2.1渲染省份列表
const provinceBox = document.querySelector('[name=province]')
async function renderProvinceList(){
    let {list} =await getProvinceList()
    let str = ''
    list.forEach(name=>{
        str += `
            <option value="${name}">${name}</option>
        `
    })
    provinceBox.innerHTML = `<option value="">--省份--</option>${str}`
}

// 2.2渲染城市列表
const cityBox = document.querySelector('[name=city]')
async function renderCityList(pname){
    let {list} =await getCityList(pname)
    let str = ''
    list.forEach(name=>{
        str += `
            <option value="${name}">${name}</option>
        `
    })
    cityBox.innerHTML = `<option value="">--城市--</option>${str}`
}

// 2.3渲染区域列表
const areaBox = document.querySelector('[name=area]')
async function renderAreaList(pname,cname){
    let {list} =await getAreaList(pname,cname)
    let str = ''
    list.forEach(name=>{
        str += `
            <option value="${name}">${name}</option>
        `
    })
    areaBox.innerHTML = `<option value="">--区域--</option>${str}`
}

//===各种事件===
// 1.编辑学生
function registerClickHanderForTbody(){
    tbodyBox.addEventListener('click',async(e)=>{
        // 1.1 TODO 删除功能
        if(e.target.className==='bi bi-trash'){
            studentId = e.target.dataset.id
            await delStudent(studentId)
            studentId = 0
            renderStudentList()
        }
        // 1.2修改功能
        if(e.target.className==='bi bi-pen'){
            studentId = e.target.dataset.id
            document.querySelector('.modal-title').innerHTML = '修改学员'
            //打开模态框
            bsModal.show()
            // 1.根据id获得学生老数据
            const {data} =await getStudentInfoData(studentId)
            // 2.数据回显到页面
            for(key in data){
                if(key=='gender'){
                const genderBox = document.querySelectorAll(`[name=gender]`)
                    genderBox[data[key]].checked = true
                }else{
                    const box = document.querySelector(`[name=${key}]`)
                        if(box){
                            box.value = data[key]
                        }
                } 
                
            }
            const {province,city,area} = data
            provinceBox.value = province
            
            await renderCityList(province)
            cityBox.value = city

            await renderAreaList(province,city)
            areaBox.value = area

        }
    })
}

//2.渲染市列表
provinceBox.addEventListener('change',(e)=>{
    //省份以改变就渲染市
    renderCityList(e.target.value)
})

// 3.渲染区列表
cityBox.addEventListener('change',(e)=>{
    renderAreaList(provinceBox.value,e.target.value)
})

// 4.点击提交学生数据
const form = document.querySelector('#form')
const btn = document.querySelector('#submit')
btn.addEventListener('click',()=>{
    const body = serialize(form,{hash:true,empty:true})
    body.age = +body.age
    body.group = +body.group
    body.salary = +body.salary
    body.hope_salary = +body.hope_salary
    body.gender = +body.gender
    console.log(body)
    //1.TODO 新增学生数据
    if(studentId==0){
        postNewStudent(body)
        bsModal.hide()
        renderStudentList()
    }else{
        // 2.修改学生数据
        putStudentInfoData(studentId,body)
        //关闭modal
        bsModal.hide()
        //id置空
        studentId = 0
        //渲染页面
        renderStudentList()
    } 
})

// 5.点击弹出新增栏
document.querySelector('#openModal').addEventListener('click',()=>{
    //弹出modal
    bsModal.show()
    document.querySelector('.modal-title').innerHTML = '新增学员'
    //获取数据
})

//===页面进入时各种初始化===
// 1.添加用户名
document.querySelector('.mb-0.text-sm.font-weight-bold.username').innerText=localStorage.getItem('username')
renderStudentList()
registerClickHanderForTbody()
renderProvinceList()
